package com.bins.music.player.controller;

import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.FileChooser;
import javafx.util.Duration;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.net.URL;
import java.util.*;

@Slf4j
public class MusicPlayerController implements Initializable {

    @FXML private Label currentTimeLabel;
    @FXML private Label totalTimeLabel;
    @FXML private Slider progressSlider;
    @FXML private Slider volumeSlider;
    @FXML private Button playButton;
    @FXML private Button pauseButton;
    @FXML private Button stopButton;
    @FXML private Button previousButton;
    @FXML private Button nextButton;
    @FXML private ListView<String> playlistView;
    @FXML private Label currentSongLabel;
    @FXML private ImageView albumArtView;
    @FXML private HBox controlBox;

    private MediaPlayer mediaPlayer;
    private ObservableList<String> playlist;
    private List<File> musicFiles;
    private int currentSongIndex = 0;
    private boolean isPlaying = false;
    private Timeline progressTimeline;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        setupUI();
        setupEventHandlers();
        playlist = FXCollections.observableArrayList();
        musicFiles = new ArrayList<>();
        playlistView.setItems(playlist);

        // 设置默认专辑封面
        try {
            Image defaultAlbumArt = new Image(Objects.requireNonNull(
                    getClass().getResourceAsStream("/images/default-album.png")));
            albumArtView.setImage(defaultAlbumArt);
        } catch (Exception e) {
            log.error("默认专辑封面加载失败: ", e);
        }
    }

    private void setupUI() {
        // 设置进度条样式
        progressSlider.setValue(0);
        progressSlider.setMax(100);

        // 设置音量条
        volumeSlider.setValue(50);
        volumeSlider.setMax(100);

        // 初始按钮状态
        updateButtonStates();

        // 设置列表视图样式
        playlistView.getSelectionModel().selectedItemProperty().addListener(
                (observable, oldValue, newValue) -> {
                    if (newValue != null) {
                        int selectedIndex = playlistView.getSelectionModel().getSelectedIndex();
                        if (selectedIndex >= 0 && selectedIndex < musicFiles.size()) {
                            playSelectedSong(selectedIndex);
                        }
                    }
                });
    }

    private void setupEventHandlers() {
        // 进度条拖动事件
        progressSlider.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (progressSlider.isValueChanging() && mediaPlayer != null) {
                double newTime = mediaPlayer.getTotalDuration().toMillis() * (newValue.doubleValue() / 100.0);
                mediaPlayer.seek(Duration.millis(newTime));
            }
        });

        // 音量控制
        volumeSlider.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (mediaPlayer != null) {
                mediaPlayer.setVolume(newValue.doubleValue() / 100.0);
            }
        });
    }

    @FXML
    private void handlePlay() {
        if (mediaPlayer != null) {
            mediaPlayer.play();
            isPlaying = true;
            updateButtonStates();
            startProgressTimer();
        }
    }

    @FXML
    private void handlePause() {
        if (mediaPlayer != null) {
            mediaPlayer.pause();
            isPlaying = false;
            updateButtonStates();
            stopProgressTimer();
        }
    }

    @FXML
    private void handleStop() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            isPlaying = false;
            updateButtonStates();
            stopProgressTimer();
            progressSlider.setValue(0);
            updateTimeLabels(Duration.ZERO, mediaPlayer.getTotalDuration());
        }
    }

    @FXML
    private void handlePrevious() {
        if (!musicFiles.isEmpty()) {
            currentSongIndex = (currentSongIndex - 1 + musicFiles.size()) % musicFiles.size();
            playSelectedSong(currentSongIndex);
        }
    }

    @FXML
    private void handleNext() {
        if (!musicFiles.isEmpty()) {
            currentSongIndex = (currentSongIndex + 1) % musicFiles.size();
            playSelectedSong(currentSongIndex);
        }
    }

    @FXML
    private void handleAddMusic() {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择音乐文件");
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("音频文件", "*.mp3", "*.wav", "*.m4a", "*.aac"),
                new FileChooser.ExtensionFilter("所有文件", "*.*")
        );

        List<File> selectedFiles = fileChooser.showOpenMultipleDialog(null);
        if (selectedFiles != null) {
            for (File file : selectedFiles) {
                if (!musicFiles.contains(file)) {
                    musicFiles.add(file);
                    playlist.add(file.getName());
                }
            }

            // 如果当前没有在播放，自动播放第一首
            if (mediaPlayer == null && !musicFiles.isEmpty()) {
                playSelectedSong(0);
            }
        }
    }

    @FXML
    private void handleRemoveMusic() {
        int selectedIndex = playlistView.getSelectionModel().getSelectedIndex();
        if (selectedIndex >= 0) {
            // 如果正在播放被删除的歌曲，先停止
            if (selectedIndex == currentSongIndex && mediaPlayer != null) {
                mediaPlayer.stop();
                mediaPlayer = null;
            }

            musicFiles.remove(selectedIndex);
            playlist.remove(selectedIndex);

            // 调整当前歌曲索引
            if (currentSongIndex >= selectedIndex) {
                currentSongIndex = Math.max(0, currentSongIndex - 1);
            }

            // 如果还有歌曲，播放当前索引的歌曲
            if (!musicFiles.isEmpty()) {
                playSelectedSong(currentSongIndex);
            } else {
                currentSongLabel.setText("没有歌曲在播放");
                albumArtView.setImage(getDefaultAlbumArt());
            }
        }
    }

    private void playSelectedSong(int index) {
        if (index < 0 || index >= musicFiles.size()) return;

        // 停止当前播放
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            stopProgressTimer();
        }

        currentSongIndex = index;
        File musicFile = musicFiles.get(index);

        try {
            Media media = new Media(musicFile.toURI().toString());
            mediaPlayer = new MediaPlayer(media);

            // 设置媒体播放器事件
            mediaPlayer.setOnReady(() -> {
                currentSongLabel.setText("正在播放: " + musicFile.getName());
                updateButtonStates();
                updateTimeLabels(Duration.ZERO, mediaPlayer.getTotalDuration());

                // 自动播放
                handlePlay();
            });

            // 自动播放下一首
            mediaPlayer.setOnEndOfMedia(this::handleNext);

            mediaPlayer.setOnError(() -> {
                log.error("媒体播放错误: {} ", mediaPlayer.getError().getMessage());
                showAlert("播放错误", "无法播放文件: " + musicFile.getName());
            });

            // 更新列表选择
            playlistView.getSelectionModel().select(index);

        } catch (Exception e) {
            log.error("创建媒体播放器失败", e);
            showAlert("错误", "无法加载文件: " + musicFile.getName());
        }
    }

    private void startProgressTimer() {
        stopProgressTimer();

        progressTimeline = new Timeline(new KeyFrame(Duration.millis(100), event -> {
            if (mediaPlayer != null) {
                Duration currentTime = mediaPlayer.getCurrentTime();
                Duration totalDuration = mediaPlayer.getTotalDuration();

                if (totalDuration.greaterThan(Duration.ZERO)) {
                    double progress = (currentTime.toMillis() / totalDuration.toMillis()) * 100.0;
                    progressSlider.setValue(progress);
                    updateTimeLabels(currentTime, totalDuration);
                }
            }
        }));
        progressTimeline.setCycleCount(Timeline.INDEFINITE);
        progressTimeline.play();
    }

    private void stopProgressTimer() {
        if (progressTimeline != null) {
            progressTimeline.stop();
        }
    }

    private void updateTimeLabels(Duration currentTime, Duration totalDuration) {
        currentTimeLabel.setText(formatTime(currentTime));
        totalTimeLabel.setText(formatTime(totalDuration));
    }

    private String formatTime(Duration duration) {
        int minutes = (int) duration.toMinutes();
        int seconds = (int) duration.toSeconds() % 60;
        return String.format("%02d:%02d", minutes, seconds);
    }

    private void updateButtonStates() {
        boolean hasMedia = mediaPlayer != null;

        playButton.setDisable(!hasMedia || isPlaying);
        pauseButton.setDisable(!hasMedia || !isPlaying);
        stopButton.setDisable(!hasMedia);
        previousButton.setDisable(musicFiles == null || musicFiles.isEmpty());
        nextButton.setDisable(musicFiles == null || musicFiles.isEmpty());
    }

    private Image getDefaultAlbumArt() {
        try {
            return new Image(Objects.requireNonNull(
                    getClass().getResourceAsStream("/images/default-album.png")));
        } catch (Exception e) {
            // 返回一个空的图像
            return new Image("/images/default-album.png", 200, 200, true, true);
        }
    }

    private void showAlert(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }

    // 清理资源
    public void cleanup() {
        stopProgressTimer();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.dispose();
        }
    }
}
